﻿const http = require('http');

const PORT = 3000;




const friends = [
    {
        id:1,
        name:'Sir Isaac Newton',
    },
    {
        id:2,
        name:'Sir Isaac',
    },
    {
        id:3,
        name:'Sir Newton',
    },
]

const server = http.createServer((req, res) => {
    const items = req.url.split('/');
    if(req.method === 'POST' && items[1] === 'friends') {
        req.on('data',(data)=>{
            const friend = data.toString();
            console.log('Request:',friend);
            friends.push(JSON.parse(friend));
            req.pipe(res);
        });
        req.pipe(res);
    } else if(req.method ==="GET" && items[1] === 'friends'){
        res.statusCode = 200;
        res.setHeader('Content-Type', 'application/json');
        if(items.length === 3){
            const friendIndex = Number(items[2]);
            res.end(JSON.stringify(friends[friendIndex]));
        }else{
            res.end(JSON.stringify(friends));
        }
    }else if(req.method ==="GET" && items[1] === 'messages'){
        res.setHeader('Content-Type', 'text/html');
        res.write('<html><body>Hello World</body></html>');
        res.end();
    }else{
        res.end(JSON.stringify(friends));
    }

});

server.listen(PORT,()=>{
    console.log(`Listening on port ${PORT}...`);
});